<template>
  <div>
    <el-table   :data="userList" :row-class-name="tableRowClassName">
      <el-table-column type="expand">
        <template #default="scope">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="用户id">{{scope.row.userId}}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{scope.row.userName}}</el-descriptions-item>
            <el-descriptions-item label="用户角色">{{roleNames[scope.row.roleId]}}</el-descriptions-item>
            <el-descriptions-item label="用户性别"> {{SEX[scope.row.userGender]}}</el-descriptions-item>
            <el-descriptions-item label="邮箱地址">{{scope.row.userEmail}}</el-descriptions-item>
            <el-descriptions-item label="账户状态">
              <el-tag :type="scope.row.userFreeze==='UN_FREEZE' ? 'success' :'info'">
                {{status[scope.row.userFreeze]}}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="注册时间">{{scope.row.registerTime}}</el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="用户id" prop="userId" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" label="用户名" prop="userName" show-overflow-tooltip></el-table-column>
      <el-table-column align="center" label="用户角色" show-overflow-tooltip>
        <template #default="scope">
         {{roleNames[scope.row.roleId]}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="邮箱地址" prop="userEmail" show-overflow-tooltip></el-table-column>
      <el-table-column width="auto" min-width="40%" align="center" label="账户状态">
        <template #default="scope">
          <el-tag :type="scope.row.userFreeze==='UN_FREEZE' ? 'success' :'info'">
            {{status[scope.row.userFreeze]}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="在线状态">
        <template #default="scope">
          <el-tag :type="userOnline.indexOf(scope.row.userId)===-1 ? 'warning' :'success'">
            {{userOnline.indexOf(scope.row.userId)===-1 ? '离线' :'在线'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :width="250" align="center">
        <template #header>
          <el-input v-model="search" style="width: 190px" placeholder="输入id,用户名,邮箱地址" >
            <template #suffix>
              <i  :class="[!loading ? 'iconfont icon-sousuo' : 'iconfont icon-jiazai1 tra']"></i>
            </template>
          </el-input>
        </template>
        <template #default="scope">
          <el-button @click="freeze(scope.row.userId,userOnline.indexOf(scope.row.userId))"
                     v-if="scope.row.userId!==$store.state.user.userId && scope.row.userFreeze!=='FREEZE'"
                     size="small" type="primary"><i class="iconfont icon-xuehua1"></i>&nbsp;冻结</el-button>

          <el-button @click="unFreeze(scope.row.userId)"
                     v-if="scope.row.userFreeze==='FREEZE'"
                     size="small" type="primary"><i class="iconfont icon-jiedong"></i>&nbsp;解冻</el-button>

          <el-button class="iconfont icon-edit-permissions"
                     size="small"
                     @click="updatePermission(scope.row.userId,'ADMIN')"
                     v-if="scope.row.userId!==$store.state.user.userId && scope.row.roleId==='USER' && scope.row.userFreeze!=='FREEZE'"
                     type="primary"> &nbsp;权限提升</el-button>
          <el-button class="iconfont icon-edit-permissions"
                     size="small"
                     @click="updatePermission(scope.row.userId,'USER')"
                     v-if="scope.row.userId!==$store.state.user.userId && scope.row.roleId==='ADMIN' && scope.row.userFreeze!=='FREEZE'"
                     type="primary"> &nbsp;权限降级</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="background-color: #ffffff;border-radius:0  0 5px 5px;justify-content: center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :pager-count=5
    />
  </div>
</template>

<script>
import {freezeAccount, getUserList, searchUser, unFreezeAccount, updateRole} from "@/api/user";

export default {
  name: "userManage",
  data(){
    return{

      roleNames:{'USER':'普通用户','ADMIN':'管理员'},
      userOnline:[],
      loading:false,
      search:'',
      SEX:{'MALE':'男','FEMALE':'女'},
      status:{'UN_FREEZE':'未冻结','FREEZE':'已冻结'},
      userList:[],
      total:0,
      currentPage:1,
      pageSize:10,
    }
  },
  watch:{
    search(newVal){
      clearTimeout(this.timeout)
      this.scenicList=[]
      if( newVal!==''){
        this.timeout=setTimeout(()=>{
          this.searchInfo(newVal)
        },2000)
      }
      else {
        this.getUsers()
      }
    },
  },
  mounted() {
    this.getUsers()
    this.$nextTick(()=>{
      setTimeout(async () => {
        this.getOnline()
      },500)

    })
  },
  methods:{
    updatePermission(userId,roleName){
      updateRole(userId,roleName).then(()=>{
        this.getUsers()
      })
    },
    //获取在线用户
    getOnline(){
      let that=this
      that.$websocket.ws.send(JSON.stringify({toName:this.$store.getters.userId,message:'getAllUsers'}))
      that.$websocket.ws.onmessage=function (event){
        const data=JSON.parse(event.data)
        if (data.message==='FREEZE'){
          that.$message({
            type:'warning',
            message:'账户被冻结'
          })
          that.logout()
        }else if (typeof data.message !=='string'){
          that.userOnline=data.message
        }
      }
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getUsers()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUsers()
    },
    searchInfo(user){
      searchUser(user).then(response=>{
        this.userList=[]
        this.userList.push(response.data.user)
        this.loading=false
      }).catch(()=>{
        this.userList=[]
        this.loading=false
      })
    },
    getUsers(){
      getUserList(this.currentPage,this.pageSize).then(response=>{
        this.userList=response.data.userList
        this.total=response.data.total
      })
    },
    freeze(userId,index){
      console.log(index)
      freezeAccount(userId).then(()=>{
        if (index!==-1)
        this.$websocket.ws.send(JSON.stringify({toName:userId,message:'FREEZE'}))
        this.getUsers()
      })
    },
    unFreeze(userId){
      unFreezeAccount(userId).then(()=>{
        this.getUsers()
      })
    },
    tableRowClassName({ row, rowIndex }){
      if (row.userFreeze==='FREEZE'){
        return 'warning-row'
      }
      return 'success-row'
    },
    logout() {
      // 将动态路由添加进路由器
      this.$store.dispatch('user/resetToken').then(() => {
        if (this.$websocket.ws&&this.$websocket.ws.readyState===1){
          this.$websocket.ws.close()
          this.$router.replace('/homepage')
        }
      })
    }
  }
}
</script>

<style>
.tra{
  animation: rotate 4s linear infinite;
}
.el-table .warning-row {
  background-color: var(--el-color-warning-lighter);
}
.el-table .success-row {
  background-color: var(--el-color-success-lighter);
}
</style>
